from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from bg.models import *
from dailyfresh.utils import *
from bg.forms import *
from datetime import datetime
from django.core.paginator import Paginator
from django.views.decorators.csrf import csrf_exempt
from django.views import View
from rest_framework.views import APIView
from django.utils.decorators import method_decorator
from django.core.cache import cache


@check_login_bg
def index(request):
    """首页"""
    # 查询缓存
    goodstype_list = cache.get("cache_index")
    # 判断
    if not goodstype_list:
        # 设置缓存
        set_cache_index()
        # 查询缓存
        goodstype_list = cache.get("cache_index")
    return render(request, "bg/index.html",locals())


def register(request):
    """注册"""
    if request.method == "GET":
        # 创建表单对象
        return render(request, "bg/register.html")
    else:
        # 创建表单对象接收参数
        form = RegisterForm(request.POST)
        # 判断格式
        if not form.is_valid():  # 未通过格式验证
            return render(request, "bg/register.html", locals())
        # 获取参数
        name = request.POST.get("name")
        password = request.POST.get("password")
        # 创建对象
        seller = Seller()
        # 赋值属性
        seller.name = name
        seller.password = encryption_md5(password)
        # 新增
        seller.save()
        # 重定向/响应
        return redirect("/bg/login/")


def login(request):
    """登录"""
    if request.method == "GET":
        return render(request, "bg/login.html")
    else:
        # 获取参数
        name = request.POST.get("name")
        password = request.POST.get("password")
        # 查询
        seller = Seller.objects.filter(name=name, password=encryption_md5(password)).first()
        # 判断
        if seller:
            # 记录登录状态
            request.session["bg_logined"] = name
            # request.session.set_expiry(60)#设置有效期，默认是2周
            return redirect("/bg/index/")
        else:
            return HttpResponse("登录失败")


@check_login_bg
def store(request):
    """店铺管理"""
    # 获取当前登录的用户
    logined = request.session.get("bg_logined")
    seller = Seller.objects.filter(name=logined).first()

    if request.method == "GET":
        # 当前登录用户的店铺
        # django orm关联对象找不到会报错RelatedObjectDoesNotExist
        try:
            store = seller.store
        except:
            store = None

        return render(request, "bg/store.html", locals())
    else:
        # 获取参数
        data = request.POST
        store_id = data.get("store_id")
        name = data.get("name")
        address = data.get("address")
        description = data.get("description")
        picture = request.FILES.get("picture")  # 文件对象
        # 判断id
        if store_id:  # 修改
            # 查询对象
            store = Store.objects.get(id=store_id)
        else:  # 新增
            # 创建对象
            store = Store()
        # 属性
        store.name = name
        store.address = address
        store.description = description
        store.lasttime = datetime.now()
        # 判断picture
        if picture:
            store.picture = picture
        store.seller = seller
        # 新增/修改
        store.save()
        # 重定向/响应
        return redirect("/bg/bg/")


@check_login_bg
def goods_list(request):
    """商品列表页"""
    # 设置每页显示的个数
    page_size = 10
    # 获取页码
    page = int(request.GET.get("page", 1))
    # 当前登录的用户
    seller = Seller.objects.filter(name=request.session.get("bg_logined")).first()
    # 查询当前用户的店铺里所有的商品
    goods_qs = seller.store.goods_set.order_by("-id").all()
    # 分页器对象,每页显示10条
    my_paginator = Paginator(goods_qs, page_size)
    # 当前页对象
    my_page = my_paginator.page(page)
    # 处理页码 前2 后2
    if page > 2:
        page_range = my_paginator.page_range[page - 3:page + 2]
    else:
        page_range = my_paginator.page_range[:5]

    # 处理编号，动态增加属性
    goods_list = my_page.object_list
    for index, goods in enumerate(goods_list):
        goods.index = (page - 1) * page_size + 1 + index  # python是动态语言，可以给对象增加/减少属性

    # 查询所有商品类型
    goodstype_list = GoodsType.objects.order_by("-id")

    return render(request, "bg/goods.html", locals())


@check_login_bg
def goods_add(request):
    """商品新增处理"""
    # 接收参数
    name = request.POST.get("name")
    goodstype_id = request.POST.get("goodstype_id")
    price = request.POST.get("price")
    shelfife = request.POST.get("shelfife")
    producttime = request.POST.get("producttime")
    number = request.POST.get("number")
    description = request.POST.get("description")
    picture = request.FILES.get("picture")
    detail = request.POST.get("detail")
    unite = request.POST.get("unite")
    # 保存文件，对象保存的时候自动实现
    # 创建对象
    goods = Goods()
    # 赋值属性
    goods.name = name
    goods.goodstype_id = goodstype_id
    goods.price = price
    goods.shelfife = shelfife
    goods.producttime = producttime
    goods.number = number
    goods.description = description
    goods.detail = detail
    goods.picture = picture
    goods.sale = 0
    goods.unite = unite

    # 获取当前登录的用户
    seller = Seller.objects.filter(name=request.session.get("bg_logined")).first()
    # 设置所属店铺
    goods.store_id = seller.store.id
    # 新增
    goods.save()

    # 重定向
    return redirect("/bg/goods/list/")


@check_login_bg
def logout(request):
    """安全退出"""
    request.session.clear()

    return redirect("/bg/login/")


###########################################################################
def test1(request):
    num = request.GET.get("num")
    if num == "1":
        info = {"name": "老王", "age": 20, "gender": True, "address": None}
    else:
        info = None
    return JsonResponse(info, json_dumps_params={"ensure_ascii": False})


def test2(request):
    """vue"""
    return render(request, "ft/test2_vue.html")

def test7_send_email(request):
    #导入包
    from django.core.mail import send_mail
    from  django.conf import settings

    #发送邮件
    send_mail(
        subject="0720",
        message="",
        from_email=settings.EMAIL_HOST_USER,
        recipient_list=["2279117458@qq.com"],
        auth_password=settings.EMAIL_HOST_PASSWORD,
        html_message="你好，<a href='http://127.0.0.1:8000/'>单击访问<strong>每日生鲜</strong>首页</a>。"
    )

    return HttpResponse("OK")
def test7_send_message(request):
    """发送短信"""
    from dailyfresh.rly import sendTemplateSMS
    import random

    phone = request.GET.get("phone","18736951452")
    sendTemplateSMS(phone, [str(random.randint(1000,9999)), 5])

    return HttpResponse("OK")

def test8_task(request):
    import  time
    time.sleep(10)
    return HttpResponse("响应好了...")


def test8_task1(request):
    from dailyfresh.tasks import  task1,task2
    #将耗时任务放入任务队列
    task1.delay()#无参任务
    # task2.delay(1,2)#有参任务

    return HttpResponse("响应好了...")